#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/2/11 21:40
# @Author  : 唐松
# @File    : conftest.py
# @Software: PyCharm

import time
from datetime import timedelta
from configs.config import read_config_file
from util_tools.notify.send_mail import SendEmail


# 彩色 ANSI 码
class Color:
    GREEN = '\033[92m'
    RED = '\033[91m'
    YELLOW = '\033[93m'
    CYAN = '\033[96m'
    RESET = '\033[0m'
    BOLD = '\033[1m'


def format_duration(seconds):
    return str(timedelta(seconds=seconds)).split('.')[0]


# 生成彩色终端打印
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    testcase_total = passed + failed + error + skipped or 0
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    dur_str = format_duration(duration)

    # 计算百分比
    def pct(num):
        return f"{(num / testcase_total) * 100:.0f}%" if testcase_total else "N/A"

        # 统一彩色 summary

    summary = f"""
    {Color.BOLD}{Color.CYAN}🏁  接口自动化测试完成{Color.RESET}
    {'=' * 80}
    {Color.GREEN}通过 : {passed:>4}  ({pct(passed)}){Color.RESET}
    {Color.RED}失败 : {failed:>4}  ({pct(failed)}){Color.RESET}
    {Color.YELLOW}错误 : {error:>4}  ({pct(error)}){Color.RESET}
    {Color.CYAN}跳过 : {skipped:>4}  ({pct(skipped)}){Color.RESET}
    {Color.BOLD}总计 : {testcase_total:>4}{Color.RESET}
    耗时 :   {dur_str} ({duration}s)
    {'=' * 80}
    """
    print(summary)

    SendEmail().send_email('接口测试框架结果', summary)
